package com.xthh.picselect;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;


import com.xt.xthh.R;
import com.xthh._function.HH_CharUtil;
import com.xthh._function.HH_Faker;
import com.xthh._function.HH_FileUtil;
import com.xthh._function.HH_Logging;
import com.xthh._function.HH_SystemUtil;
import com.xthh._function._ini.HH_INI;
import com.xthh._function._language.HH_LanguageUtil;
import com.xthh._msg.HH_MSG;
import com.xthh._struct.HH_T_FileInfo;
import com.xthh._struct.HH_T_FolderSearch;
import com.xthh._struct.HH_T_SystemParams;
import com.xthh.picselect.HH_AdapterFileSelectManage2;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;

public class HH_Activity_PicFileSelect extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = "FileSelect_Activity2";
    public static final String FIND_FILE_EXT = "FIND_FILE_EXT";
    public static final String GET_FOLDER_DETAILS_INFO = "GET_FOLDER_DETAILS_INFO";





    Context ctx;
    LinearLayout linearlayout_return;
    LinearLayout linearlayout_left;
    TextView textView_title;
    TextView textview_path;
    ArrayList<String> listExts = new ArrayList<>();
    ArrayList<HH_T_FolderSearch> listSearchInfo = new ArrayList<>();
    private HH_AdapterFileSelectManage2 mAdapterFileSelectManage2;
    public static HandlenRecvMessage handlenRecvMessage;
    HH_T_SystemParams systemParams;
    private final int MAX_DOWN_THREAD_COUNT = 10;
    private HashMap<String, Integer> hashMapGetFileCount = new HashMap<String, Integer>();
    List<List<String>> listGetFileCount = new ArrayList<List<String>>();
    String strCurrentSearchPath = Environment.getExternalStorageDirectory().getPath();

    // true,表示将获取子文件夹里指定扩展名的文件个数，如果文件多，耗时久，但只显示有效的文件夹
    // false,表示不获取文件夹的文件个数，运行速度快，但显示的文件夹多
    boolean bGetFileDetailsInfo = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pic_file_select);
        ctx = this;

        listExts = (ArrayList<String>) getIntent().getStringArrayListExtra(FIND_FILE_EXT);
        bGetFileDetailsInfo = getIntent().getBooleanExtra(GET_FOLDER_DETAILS_INFO, false);

        // 设置状态栏字体颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
            getWindow().setStatusBarColor(getColor(R.color.transparent));
            getWindow().setNavigationBarColor(getColor(R.color.transparent));
        }

        HH_LanguageUtil.SetCurrentLanguange(this);
        initView();
        handlenRecvMessage = new HandlenRecvMessage();


        systemParams = new HH_T_SystemParams(getApplication(), ctx, handlenRecvMessage);

        mAdapterFileSelectManage2.removeAll();
        SearchFileInfo(strCurrentSearchPath);

        // 设置10个线程同时下载
        for (int i = 0; i < MAX_DOWN_THREAD_COUNT; i++){
            listGetFileCount.add(new ArrayList<>());
        }

        for (int i = 0; i < MAX_DOWN_THREAD_COUNT; i++){
            CreateGetFileCountThread(i);
        }
    }


    private void LoadGetCount(String picPath) {
        if (picPath == null || picPath.length() <= 0)
            return;
        if (listGetFileCount == null || listGetFileCount.size() <= 0)
            return;

        int[] numbers = new int[listGetFileCount.size()];
        for (int i = 0; i < listGetFileCount.size(); i++){
            if (listGetFileCount.get(i) != null)
                numbers[i] = listGetFileCount.get(i).size();
        }

        for (int i = 0; i < listGetFileCount.size(); i++){
            List<String> lt = listGetFileCount.get(i);
            if (lt != null){
                for (int j = 0; j < lt.size(); j++){
                    if (HH_CharUtil.Strcmp(lt.get(j), picPath, true)){
                        return;
                    }
                }
            }
        }

        bubbleSort(numbers);

        if (numbers == null || numbers.length <= 0)
            return;

        for (int i = 0; i < listGetFileCount.size(); i++){
            if (listGetFileCount.get(i) != null){
                if (listGetFileCount.get(i).size() == numbers[0]){
                    listGetFileCount.get(i).add(picPath);
                    break;
                }
            }
        }
    }


    public static void bubbleSort(int[] array) {
        int n = array.length;
        boolean swapped;

        for (int i = 0; i < n - 1; i++) {
            swapped = false;

            for (int j = 0; j < n - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    // Swap elements
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;

                    swapped = true;
                }
            }

            if (!swapped) {
                break;
            }
        }
    }


    private void CreateGetFileCountThread(int index) {
        new Thread() {
            @Override
            public void run() {
                while (true){
                    if (listGetFileCount.get(index) != null && listGetFileCount.get(index).size() > 0){
                        String picPath = listGetFileCount.get(index).get(0);
                        if (picPath != null && HH_FileUtil.IsExists(picPath)){
                            HH_Logging.i(TAG, "begin = %s", picPath);
                            //int count = GetFolderFiles(picPath);
                            int count = 0;
                            if (bGetFileDetailsInfo){
                                count = GetFolderFiles(picPath);
                            } else {
                                count = 1;
                            }

                            HH_Logging.i(TAG, "begin = %s-finish", picPath);
                            hashMapGetFileCount.put(picPath, count);
                            if (count > 0){
                                HH_SystemUtil.SendMessage(systemParams, HH_MSG.DISPLAY_LIST_2_FOLDER, picPath, count, 0);
                            }
                        }

                        // 删除这个
                        if (listGetFileCount.get(index) != null && listGetFileCount.get(index).size() > 0)
                            listGetFileCount.get(index).remove(0);
                    }
                    HH_SystemUtil.Sleep(10);
                }
            }

        }.start();
    }

    private void GetFoldeFileInfo(File path, ArrayList<String> exts) {
        if (path == null || exts == null || exts.size() <= 0)
            return;

        File[] files = path.listFiles();
        if (files == null)
            return;

        listSearchInfo = new ArrayList<>();
        for (int i = 0; i < files.length; i++){
            if (!files[i].isHidden()){
                if (files[i].isFile()){
                    boolean isPic = HH_FileUtil.CheckFile(files[i].getPath(), exts);
                    if (isPic){
                        HH_SystemUtil.SendMessage(systemParams, HH_MSG.DISPLAY_LIST_3_FILE, files[i].getPath(), 0, 0);
                    }

                } else if (files[i].isDirectory()){
                    Integer count = hashMapGetFileCount.get(files[i].getPath());
                    if (count == null){
                        LoadGetCount(files[i].getPath());
                    }
                    else{
                        if (count > 0)
                            HH_SystemUtil.SendMessage(systemParams, HH_MSG.DISPLAY_LIST_2_FOLDER, files[i].getPath(), count, 0);
                    }
                }
            }
        }

        return;
    }

    public int GetFolderFiles(String path){
        ArrayList<File> files = new ArrayList<>();

        File rootFile = new File(path);
        HH_Faker faker = new HH_Faker();
        try {
            files = faker.computeAllFile(rootFile, new Function<File, Boolean>() {
                @Override
                public Boolean apply(File file) {
                    return HH_FileUtil.CheckFile(file.getPath(), listExts);
                }
            });
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (files != null){
            return files.size();
        }

        return 0;
    }

    // 监听各种状态
    public class HandlenRecvMessage extends Handler {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case HH_MSG.DISPLAY_LIST:{
                    mAdapterFileSelectManage2.notifyDataSetChanged();
                    break;
                }
                case HH_MSG.DISPLAY_LIST_2_FOLDER:{
                    mAdapterFileSelectManage2.addDevice_0(new HH_T_FolderSearch((String)msg.obj, false, null, msg.arg1, false));
                    mAdapterFileSelectManage2.notifyDataSetChanged();
                    break;
                }
                case HH_MSG.DISPLAY_LIST_3_FILE:{
                    mAdapterFileSelectManage2.addDevice(new HH_T_FolderSearch((String)msg.obj, true, null, 0, false));
                    mAdapterFileSelectManage2.notifyDataSetChanged();
                    break;
                }
            }
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    private void initView() {
        textView_title = findViewById(R.id.textView_title);
        textview_path = findViewById(R.id.textview_path);
        linearlayout_return = findViewById(R.id.linearlayout_return);
        linearlayout_return.setOnClickListener(this);
        linearlayout_left = findViewById(R.id.linearlayout_left);
        linearlayout_left.setOnClickListener(this);

        mAdapterFileSelectManage2 = new HH_AdapterFileSelectManage2(this, listExts, bGetFileDetailsInfo);
        // 列表点击事件
        mAdapterFileSelectManage2.setOnModelClickListener(new HH_AdapterFileSelectManage2.OnSelectListener() {

            @Override
            public void onSelect(HH_T_FolderSearch lfi, int index) {
                List<HH_T_FolderSearch> list = mAdapterFileSelectManage2.GetAll();
                if (list != null){
                    for (int i = 0; i < list.size(); i++){
                        list.get(i).setSelect(index == i);
                    }
                }
                mAdapterFileSelectManage2.notifyDataSetChanged();

                if (lfi.isFile()){

                    Intent result = new Intent();
                    result.putExtra("IMPORT_PATH_FILE", lfi.getPath());
                    setResult(RESULT_OK, result);
                    finish();

                } else {
                    int runCount = GetLoadFailCount();
                    if (runCount> 0){
                        return;
                    }


                    strCurrentSearchPath = lfi.getPath();
                    mAdapterFileSelectManage2.removeAll();
                    //SystemUtil.SendMessageFont_FileSelect_Activity2(MSG.DISPLAY_LIST, "", 0, 0);
                    mAdapterFileSelectManage2.notifyDataSetChanged();
                    SearchFileInfo(strCurrentSearchPath);
                }
            }

            @Override
            public void onSelectL(int index) {
                List<HH_T_FolderSearch> list = mAdapterFileSelectManage2.GetAll();
                if (list != null){
                    for (int i = 0; i < list.size(); i++){
                        list.get(i).setSelect(index == i);
                    }
                }
                mAdapterFileSelectManage2.notifyDataSetChanged();
            }
        });
        ListView listView_name = (ListView) findViewById(R.id.list_name);
        listView_name.setAdapter(mAdapterFileSelectManage2);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void SearchFileInfo(String path){
        HH_INI.putString(systemParams, "TEMP_SAVE_PATH2", path);
        String temp = HH_INI.getString(systemParams, "TEMP_SAVE_PATH2");
        temp = temp.replace(Environment.getExternalStorageDirectory().getPath(), getString(R.string.strID_371));
        textview_path.setText(temp);

        Thread thread = new Thread(){
            @Override
            public void run() {
                GetFoldeFileInfo(new File(path), listExts);
            }
        };
        thread.start();
        thread = null;
    }

    public HH_T_FileInfo GetFileInfo(String path) {

        File f = new File(path);
        if (f.exists()) {
            try {
                String timeChange = new SimpleDateFormat("yyyy-MM-dd").format(new Date(f.lastModified()));
                return new HH_T_FileInfo(timeChange,
                        ShowLongFileSzie(f.length()),
                        f.getName(),
                        path,
                        getString(R.string.strID_371) + path.substring(Environment.getExternalStorageDirectory().getPath().length()),
                        false);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return new HH_T_FileInfo();
    }

    /****
     * 计算文件大小
     *
     * @param length
     * @return
     */
    public String ShowLongFileSzie(Long length) {
        if (length >= 1048576) {
            return (length / 1048576) + "MB";
        } else if (length >= 1024) {
            return (length / 1024) + "KB";
        } else if (length < 1024) {
            return length + "B";
        } else {
            return "0KB";
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.linearlayout_return) {
            finish();
        } else if (id == R.id.linearlayout_left) {
            int runCount = GetLoadFailCount();
            if (runCount > 0) {
                return;
            }

            if (HH_CharUtil.Strcmp(strCurrentSearchPath, Environment.getExternalStorageDirectory().getPath(), true)) {
                return;
            }

            int x = strCurrentSearchPath.lastIndexOf("/");
            strCurrentSearchPath = strCurrentSearchPath.substring(0, x);
            mAdapterFileSelectManage2.removeAll();
            mAdapterFileSelectManage2.notifyDataSetChanged();
            SearchFileInfo(strCurrentSearchPath);
        }
    }

    private int GetLoadFailCount() {
        int count = 0;
        for (int i = 0; i < listGetFileCount.size(); i++){
            count += listGetFileCount.get(i).size();
        }

        return count;
    }
}
